<script>
  // 引入状态
  import { cards } from "./store";
  import { saveAs } from "file-saver";
  // import { getNowDateFormat } from "./utils";

  let title = "";
  let content = "";

  function doAdd() {
    console.log('add')
    // 校验
    if (!title || !content) {
      alert("标题和内容必须都填！");
      return;
    }

    console.log()
    // 更新卡片状态，追加一个新卡片
    cards.update((item) => {
      item = [
        ...item,
        {
          title,
          content,
          creationTime: getNowDateFormat('yyyy-MM-dd HH:mm:ss'),
        },
      ];
      return item;
    });
  }

  function getNowDateFormat(fmt) {
    let date = new Date();
    var o = {
      "M+": date.getMonth() + 1,
      "d+": date.getDate(),
      "H+": date.getHours(),
      "m+": date.getMinutes(),
      "s+": date.getSeconds(),
      "q+": Math.floor((date.getMonth() + 3) / 3),
      S: date.getMilliseconds(),
    };
    if (/(y+)/.test(fmt))
      fmt = fmt.replace(
        RegExp.$1,
        (date.getFullYear() + "").substr(4 - RegExp.$1.length)
      );
    for (var k in o)
      if (new RegExp("(" + k + ")").test(fmt))
        fmt = fmt.replace(
          RegExp.$1,
          RegExp.$1.length == 1
            ? o[k]
            : ("00" + o[k]).substr(("" + o[k]).length)
        );
    return fmt;
  }

  // 导出为 read_note.md 文件
  function doExport() {
    const texts = [];
    // 读取 cards 状态数组
    for (const card of $cards) {
      let text = `### ${card.title}\n${card.content}\n${card.creationTime}\n`;
      texts.push(text);
    }
    // 写入文件
    const blob = new Blob(texts, { type: "text/plain;charset=utf-8" });
    saveAs(blob, "read_note.md");
  }
</script>

<style>
  /* 操作面板固定在页面底部 */
  .add-card {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    box-sizing: border-box;
    padding: 1rem;
    background: linear-gradient(to right,#fbc2eb, #a6c1ee);
    display: flex;
  }

  .input-wrapper {
    flex: 4; /* 使用 Flex 布局 */
    flex-direction: column;
  }

  .input-title {
    width: 100%;
  }

  .input-content {
    width: 100%;
  }

  .add-btn,
  .export-btn {
    flex: 1;
    margin-left: 1rem;
    color: #666;
  }
</style>

<div class="add-card">
  <div class="input-wrapper">
    <input
      class="input-title"
      type="text"
      placeholder="输入标题"
      bind:value={title} />
    <textarea
      class="input-content"
      placeholder="输入内容"
      bind:value={content} />
  </div>
  <button class="add-btn" on:click={doAdd}>添加</button>
  <button class="export-btn" on:click={doExport}>导出</button>
</div>
